package com.bawei.property.view

import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.base.RoutePath
import com.bawei.common.mvi.BaseMviActivity
import com.bawei.image.GlideEngine
import com.bawei.property.R
import com.bawei.property.adapter.CarImgListAdapter
import com.bawei.property.adapter.ColorListAdapter
import com.bawei.property.databinding.ActivityEditParkBinding
import com.bawei.property.entity.CarImageEntity
import com.bawei.property.entity.ColorValue
import com.bawei.property.entity.ParkValue
import com.bawei.property.intent.ParkViewIntent
import com.bawei.property.state.ParkUiState
import com.bawei.property.vm.ParkViewModel
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.ArrayList
import java.util.Date

@Route(path = RoutePath.PATH_EDIT_PARK_PAGE)
class EditParkActivity : BaseMviActivity<ActivityEditParkBinding>() {

    private val mViewModel: ParkViewModel by viewModels()

    private lateinit var mColorListAdapter: ColorListAdapter
    private lateinit var mImgListAdapter: CarImgListAdapter

    private var mCarImageList = mutableListOf<CarImageEntity>()

    @Autowired
    lateinit var parkEntity: ParkValue

    override fun getLayoutId(): Int = R.layout.activity_edit_park

    override fun initView() {
        //使用ARouter对成员变量进行初始化
        ARouter.getInstance().inject(this)
        mDataBinding.includePageTitle.ivBack.setOnClickListener {
            this@EditParkActivity.finish()
        }
        mDataBinding.includePageTitle.tvTitle.text = "车位信息修改"
        //初始化车位信息
        initParkData()
    }

    private fun initParkData() {
//        var startDate = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date(parkEntity.parkStart.toLong() * 1000L)).toString()
//        var endDate =  SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date(parkEntity.parkEnd.toLong() * 1000L)).toString()
        mDataBinding.tvApplyDate.text = "${parkEntity.parkStart} - ${parkEntity.parkEnd}"
        mDataBinding.tvApplyName.text = parkEntity.parkName
        mDataBinding.tvApplyDate.text = parkEntity.parkTime //SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date(parkEntity.parkTime.toLong() * 1000L)).toString()

        //车辆颜色
        mDataBinding.rvCarColors.layoutManager = LinearLayoutManager(this@EditParkActivity, LinearLayoutManager.HORIZONTAL, false)
        mColorListAdapter = ColorListAdapter(R.layout.item_color_layout)
        mDataBinding.rvCarColors.adapter = mColorListAdapter

        //车辆图片
        mDataBinding.rvCarImgs.layoutManager = LinearLayoutManager(this@EditParkActivity, LinearLayoutManager.HORIZONTAL, false)
        mImgListAdapter = CarImgListAdapter(R.layout.item_car_img)
        mDataBinding.rvCarImgs.adapter = mImgListAdapter

        //添加车辆图片
        mDataBinding.ivAddCarImg.setOnClickListener {
            PictureSelector.create(this@EditParkActivity)
                .openGallery(SelectMimeType.ofImage())
                .setImageEngine(GlideEngine.createGlideEngine())
                .forResult(object : OnResultCallbackListener<LocalMedia>{
                    override fun onResult(result: ArrayList<LocalMedia>) {
                        //获取返回图片
                        result.forEach {
                            mCarImageList.add(CarImageEntity(it.availablePath, it.availablePath.substring(it.availablePath.lastIndexOf("/") + 1)))
                        }
                        mImgListAdapter.data.addAll(mCarImageList)
                        mImgListAdapter.notifyDataSetChanged()

                        //上传图片
                        uploadCarImages(mCarImageList)
                    }

                    override fun onCancel() {

                    }
                })

        }

        //提交车辆信息
        mDataBinding.tvSubmit.setOnClickListener {
            lifecycleScope.launch {
                mViewModel.channel.send(ParkViewIntent.SubmitParkInfo({}))
            }
        }
    }


    /**
     * 发起图片上传
     */
    private fun uploadCarImages(list: MutableList<CarImageEntity>){
        lifecycleScope.launch {
            mViewModel.channel.send(ParkViewIntent.UploadCarImages(list as List<CarImageEntity>))
        }
    }

    override suspend fun sendViewIntent() {
        mViewModel.channel.send(ParkViewIntent.LoadColorList)
    }

    override suspend fun collectUiState() {
        mViewModel.uiState.collect{
            when(it){
                is ParkUiState.LoadColorListSuccess -> {
                    //更新颜色列表
                    mColorListAdapter.data.addAll(it.data as MutableList<ColorValue>)
                    mColorListAdapter.notifyDataSetChanged()
                }
                is ParkUiState.UploadImageSuccess -> {
                    showToastMsg("上传成功！！")
                    LogUtils.i("上传成功返回的图片地址：${GsonUtils.toJson(it.data)}")
                }
                is ParkUiState.LoadColorListFail -> showToastMsg(it.msg)
                is ParkUiState.UploadImageFail -> showToastMsg(it.msg)
                else -> {}

            }


        }

    }


}